<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket Chat Room</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/protobufjs/6.11.2/protobuf.min.js"></script>
    <script>
        let socket;
        let root; // 用于存储 Protobuf 的根对象
        let MessageType; // 存储枚举类型

        // 加载 Protobuf 定义
        protobuf.load('path/to/chat_message.proto', (err, loadedRoot) => {
            if (err) throw err;
            root = loadedRoot;
            MessageType = root.lookupEnum("test.abcode.protobuf.chatroom.MessageType"); // 存储枚举
            initializeWebSocket();
        });

        // 初始化 WebSocket
        function initializeWebSocket() {
            socket = new WebSocket('ws://localhost:8080/chat'); // 请根据实际情况修改 URL

            socket.addEventListener('open', (event) => {
                console.log('Connected to WebSocket');
                // 发送心跳
                sendHeartbeat();
            });

            socket.addEventListener('message', (event) => {
                const gameMessage = parseGameMessage(event.data);
                handleGameMessage(gameMessage);
            });

            socket.addEventListener('close', (event) => {
                console.log('WebSocket connection closed');
            });
        }

        // 发送心跳
        function sendHeartbeat() {
            const heartbeatMessage = {
                type: MessageType.values.HEARTBEAT, // 使用枚举
                content: new Uint8Array() // 空内容
            };
            sendMessage(heartbeatMessage);
        }

        // 加入房间
        function joinRoom(userId, nickname) {
            const User = root.lookupType("test.abcode.protobuf.chatroom.User");
            const userPayload = {
                user_id: userId,
                nickname: nickname,
                is_host: false
            };

            const errMsg = User.verify(userPayload);
            if (errMsg) throw Error(errMsg);
            const userBuffer = User.encode(User.create(userPayload)).finish();

            const joinRoomMessage = {
                type: MessageType.values.JOIN_ROOM, // 使用枚举
                content: userBuffer // 将编码后的二进制内容作为 content
            };

            sendMessage(joinRoomMessage);
        }

        // 发送消息
        function sendMessageToRoom(content) {
            const sendMsgMessage = {
                type: MessageType.values.SEND_MESSAGE, // 使用枚举
                content: {
                    content: content
                }
            };
            sendMessage(sendMsgMessage);
        }

        // 离开房间
        function leaveRoom(userId) {
            const leaveRoomMessage = {
                type: MessageType.values.LEAVE_ROOM, // 使用枚举
                content: {
                    user_id: userId
                }
            };
            sendMessage(leaveRoomMessage);
        }

        // 发送消息到 WebSocket
        function sendMessage(message) {
            const encodedMessage = encodeGameMessage(message);
            socket.send(encodedMessage);
        }

        // 处理接收到的游戏消息
        function handleGameMessage(gameMessage) {
            switch (gameMessage.type) {
                case MessageType.values.HEARTBEAT_RES: // 使用枚举
                    console.log('Heartbeat response received');
                    break;
                case MessageType.values.JOIN_ROOM_NOTICE: // 使用枚举
                    const joinNotice = parseJoinNotice(gameMessage.content);
                    console.log('Join room notice:', joinNotice);
                    break;
                case MessageType.values.SEND_MESSAGE_NOTICE: // 使用枚举
                    const sendMsgNotice = parseSendMsgNotice(gameMessage.content);
                    console.log('Message received:', sendMsgNotice);
                    break;
                case MessageType.values.LEAVE_ROOM_NOTICE: // 使用枚举
                    const leaveNotice = parseLeaveNotice(gameMessage.content);
                    console.log('Leave room notice:', leaveNotice);
                    break;
                default:
                    console.log('Unknown message type:', gameMessage.type);
            }
        }

        // 解析 GameMessage
        function parseGameMessage(data) {
            const GameMessage = root.lookupType("test.abcode.protobuf.chatroom.GameMessage");
            const decodedMessage = GameMessage.decode(new Uint8Array(data));
            return decodedMessage;
        }

        // 编码 GameMessage
        function encodeGameMessage(message) {
            const GameMessage = root.lookupType("test.abcode.protobuf.chatroom.GameMessage");
            const errMsg = GameMessage.verify(message);
            if (errMsg) throw Error(errMsg);
            const encodedMessage = GameMessage.encode(GameMessage.create(message)).finish();
            return encodedMessage;
        }

        // 解析加入房间通知
        function parseJoinNotice(content) {
            const JoinNotice = root.lookupType("test.abcode.protobuf.chatroom.JoinRoomNotice");
            return JoinNotice.decode(new Uint8Array(content));
        }

        // 解析发送消息通知
        function parseSendMsgNotice(content) {
            const SendMsgNotice = root.lookupType("test.abcode.protobuf.chatroom.SendMessageNotice");
            return SendMsgNotice.decode(new Uint8Array(content));
        }

        // 解析离开房间通知
        function parseLeaveNotice(content) {
            const LeaveNotice = root.lookupType("test.abcode.protobuf.chatroom.LeaveRoomNotice");
            return LeaveNotice.decode(new Uint8Array(content));
        }
    </script>
</head>
<body>
<h1>WebSocket Chat Room</h1>
<button onclick="joinRoom('user123', 'Alice')">Join Room</button>
<button onclick="sendMessageToRoom('Hello, everyone!')">Send Message</button>
<button onclick="leaveRoom('user123')">Leave Room</button>
</body>
</html>
